package com.weihao.activiti6.controller;

import com.weihao.activiti6.model.Leave;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/leave/v1")
public class LeaveController {

    private static final Logger log = LoggerFactory.getLogger(LeaveController.class);

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ProcessEngine processEngine;

    /**
     * 启动流程
     * @param userId
     * @return
     */
    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public Map<String, Object> start(@RequestParam String userId){
        Map<String, Object> vars = new HashMap<>();
        Leave leave = new Leave();
        leave.setUserId(userId);
        vars.put("leave",leave);
        vars.put("userId", userId);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leave1",vars);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code","0");
        resultMap.put("msg","ok");
        return resultMap;
    }

    /**
     * 填写请假单
     * @param leave
     * @return
     */
    @RequestMapping(value="/apply", method = RequestMethod.POST)
    public Map<String, Object> apply(@RequestBody Leave leave){
        Task task = taskService.createTaskQuery().taskId(leave.getTaskId()).singleResult();
        Map<String, Object> vars = new HashMap<>();
        Leave origin = (Leave) taskService.getVariable(leave.getTaskId(), "leave");
        origin.setDesc(leave.getDesc());
        origin.setStartDate(leave.getStartDate());
        origin.setEndDate(leave.getEndDate());
        origin.setTotalDay(leave.getTotalDay());
        origin.setApprover1(leave.getApprover1());
        origin.setApprover2(leave.getApprover2());
        origin.setSubmit(leave.getSubmit());
        vars.put("leave", origin);
        taskService.complete(leave.getTaskId(), vars);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code","0");
        resultMap.put("msg","ok");
        return resultMap;
    }

    /**
     * 查询用户流程
     * @param userId
     * @return
     */
    @RequestMapping(value = "/find", method = RequestMethod.GET)
    public Map<String, Object> find(@RequestParam("userId")String userId){
        List<Task> taskList = taskService.createTaskQuery().taskAssignee(userId).list();
        List<Leave> resultList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(taskList)){
            for(Task task : taskList){
                Leave leave = (Leave) taskService.getVariable(task.getId(),"leave");
                leave.setTaskId(task.getId());
                leave.setTaskName(task.getName());
                resultList.add(leave);
            }
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code","0");
        resultMap.put("msg","ok");
        resultMap.put("datas", resultList);
        return resultMap;
    }

    /**
     * 直接主管审批
     * @param leave
     * @return
     */
    @RequestMapping(value = "/approve1", method = RequestMethod.POST)
    public Map<String, Object> approve1(@RequestBody Leave leave){
        taskService.createTaskQuery().taskId(leave.getTaskId()).singleResult();
        Map<String, Object> vars = new HashMap<>();
        Leave origin = (Leave) taskService.getVariable(leave.getTaskId(), "leave");
        origin.setApproveDesc1(leave.getApproveDesc1());
        origin.setAgree1(leave.getAgree1());
        vars.put("leave", origin);
        taskService.complete(leave.getTaskId(),vars);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code","0");
        resultMap.put("msg","ok");
        return resultMap;
    }

    /**
     * 部门主管审批
     * @param leave
     * @return
     */
    @RequestMapping(value = "/approve2", method = RequestMethod.POST)
    public Map<String, Object> approve2(@RequestBody Leave leave){
        Task task = taskService.createTaskQuery().taskId(leave.getTaskId()).singleResult();
        Map<String, Object> vars = new HashMap<>();
        Leave origin = (Leave) taskService.getVariable(leave.getTaskId(), "leave");
        origin.setApproveDesc2(leave.getApproveDesc2());
        origin.setAgree2(leave.getAgree2());
        vars.put("leave", origin);
        taskService.complete(leave.getTaskId(),vars);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code","0");
        resultMap.put("msg","ok");
        return resultMap;
    }

    /**
     * 查看我的流程历史记录
     * @param userId
     * @return
     */
    @RequestMapping(value="/findClosed", method = RequestMethod.GET)
    public Map<String, Object> findClosed(@RequestParam String userId){
        HistoryService historyService = processEngine.getHistoryService();

        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().processDefinitionKey("leave1").includeProcessVariables().orderByProcessInstanceStartTime().desc().variableValueEquals("userId", userId).list();
        List<Leave> leaves = new ArrayList<>();
        for(HistoricProcessInstance pi : list){
            leaves.add((Leave) pi.getProcessVariables().get("leave"));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code","0");
        resultMap.put("msg","ok");
        resultMap.put("datas", leaves);
        return resultMap;
    }

    /**
     * 查询我参与的流程
     * @param userId
     * @return
     */
    @RequestMapping(value = "/findHistoryRelated", method = RequestMethod.GET)
    public Map<String, Object> findHistoryRelated(@RequestParam String userId){
        HistoryService historyService = processEngine.getHistoryService();
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery().processDefinitionKey("leave1").includeProcessVariables().taskAssignee(userId).listPage(1,15);
        List<Leave> leaves = new ArrayList<>();
        for(HistoricTaskInstance task : taskList){
            leaves.add((Leave) task.getProcessVariables().get("leave"));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "ok");
        resultMap.put("datas", leaves);
        return resultMap;
    }
}
